package com.gton.lpl.config;

import com.gton.lpl.filter.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.mail.Session;
import java.util.Properties;

/**
 * @description: SpringBoot-Web配置
 * @author: GuoTong
 * @createTime: 2021-10-05 15:37
 * @since JDK 1.8 OR 11
 **/
@Configuration
public class SpringBootConfig implements WebMvcConfigurer {

    @Value("${spring.mail.host}")
    private String emailHost;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Value("${spring.mail.default-encoding}")
    private String encoding;


    /**
     * Description:  添加全局跨域CORS处理
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("http://127.0.0.1:8080")
                // 是否允许证书
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }


    /**
     * Description: 静态资源过滤
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //ClassPath:/Static/** 静态资源释放
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        //释放swagger
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        //释放webjars
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * Description:添加基于JWT认证的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截所有请求，通过判断是否有 @SkipTokenByJWT 注解 决定是否需要登录
        registry.addInterceptor(getInterceptorByJwt()).addPathPatterns("/**");

    }

    /**
     * Description: JWT 登录校验拦截器
     */
    @Bean
    public AuthenticationInterceptor getInterceptorByJwt() {
        return new AuthenticationInterceptor();
    }


    /**
     * Description:  邮箱工具类注册
     * Springboot 2.6之后 JavaMailSender不再由Spring容器托管，需要自己注册
     * password 是来自于邮箱的授权码！注意邮箱密码改变或者长时间没用建议重新生成授权码：
     *
     * @author: GuoTong
     * @date: 2022-08-12 18:03:39
     */
    @Bean
    public JavaMailSender getMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(password);
        javaMailSender.setDefaultEncoding(encoding);
        javaMailSender.setHost(emailHost);
        javaMailSender.setPort(465);
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.ssl.enable", "true");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", emailHost);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 须要请求认证
        javaMailSender.setJavaMailProperties(props);
        // 2. 根据配置建立会话对象, 用于和邮件服务器交互
        Session session = Session.getInstance(props);
        javaMailSender.setSession(session);
        return javaMailSender;
    }
}
